package web;

import com.alibaba.fastjson2.JSONObject;
import core.AjaxResult;
import domain.AdminUser;
import service.AdminUserService;
import service.impl.AdminUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * @author 于金鹏
 * @Date 2024/12/20 9:44
 * @Package StudentCheckSystem
 */
@WebServlet("/register")
public class UserRegisterServlet extends HttpServlet {

    private AdminUserService userService = new AdminUserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter writer = resp.getWriter();
        try {
            // 解析请求体中的JSON数据
            BufferedReader reader = req.getReader();
            StringBuilder requestBody = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }
            JSONObject jsonObject = JSONObject.parseObject(requestBody.toString());
            AdminUser user = new AdminUser();
            user.setUserName(jsonObject.getString("username"));
            user.setSex(jsonObject.getInteger("sex"));
            user.setPassword(jsonObject.getString("admin_password"));
            user.setEmail(jsonObject.getString("email"));
            user.setPhone(jsonObject.getString("phone"));
            userService.register(user);
            // 注册成功，构建并返回包含成功信息和相关数据（这里可按需调整返回的具体数据内容）的AjaxResult对象
            AjaxResult<Object> successResult = AjaxResult.success(user);
            writer.write(JSONObject.toJSONString(successResult));
        } catch (SQLException e) {
            // 数据库操作出现错误，构建并返回包含对应错误码和详细错误消息的AjaxResult对象
            AjaxResult<Object> errorResult = AjaxResult.error(500, "数据库操作出现错误：" + e.getMessage());
            writer.write(JSONObject.toJSONString(errorResult));
            e.printStackTrace();
        }
    }
}
